import argparse
import sys
from types import MethodType

import torch
from mmcv import Config, DictAction
from mmcv.runner import load_checkpoint

from mmdet.models import build_detector

sys.path.append(
    "/workspace/volume/wangxianzhuo-data/iva_detection/tools/model_converters"
)
from merge_repvgg import repvgg_model_convert

try:
    from mmcv.cnn import get_model_complexity_info
except ImportError:
    raise ImportError("Please upgrade mmcv to >0.6.2")


def parse_args():
    parser = argparse.ArgumentParser(description="Train a detector")
    parser.add_argument("config", help="train config file path")
    parser.add_argument("checkpoint", help="checkpoint to convert")
    parser.add_argument("out_file", help="name of output file")
    parser.add_argument(
        "--shape", type=int, nargs="+", default=[544, 960], help="input image size"
    )
    parser.add_argument(
        "--cfg-options",
        nargs="+",
        action=DictAction,
        help="override some settings in the used config, the key-value pair "
        "in xxx=yyy format will be merged into config file. If the value to "
        'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
        'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
        "Note that the quotation marks are necessary and that no white space "
        "is allowed.",
    )
    args = parser.parse_args()
    return args


def flatten(outputs):
    out = []
    for o in outputs:
        if isinstance(o, (tuple, list)):
            out.extend(flatten(o))
        else:
            out.append(o)
    return tuple(out)


def forward(self, inputs):
    out = self.forward_dummy(inputs)
    return flatten(out)


def main():

    args = parse_args()

    if len(args.shape) == 1:
        input_shape = (3, args.shape[0], args.shape[0])
    elif len(args.shape) == 2:
        input_shape = (3,) + tuple(args.shape)
    else:
        raise ValueError("invalid input shape")

    cfg = Config.fromfile(args.config)
    if args.cfg_options is not None:
        cfg.merge_from_dict(args.cfg_options)
    # import modules from string list.
    if cfg.get("custom_imports", None):
        from mmcv.utils import import_modules_from_strings

        import_modules_from_strings(**cfg["custom_imports"])

    if cfg.model.backbone.type == "RepVGG":
        model = repvgg_model_convert(cfg, args.checkpoint)
    else:
        model = build_detector(
            cfg.model, train_cfg=cfg.get("train_cfg"), test_cfg=cfg.get("test_cfg")
        )
    load_checkpoint(model, args.checkpoint, map_location="cpu")
    model.eval()

    if hasattr(model, "forward_dummy"):
        model.forward = MethodType(forward, model)
        # model.forward = model.forward_dummy
    else:
        raise NotImplementedError(
            "FLOPs counter is currently not currently supported with {}".format(
                model.__class__.__name__
            )
        )

    input_tensor = torch.rand(1, *input_shape)
    print(input_tensor.dtype)
    trace_model = torch.jit.trace(model, input_tensor)
    torch.jit.save(trace_model, args.out_file)
    print(f"Model save as {args.out_file}")


if __name__ == "__main__":
    main()
